package com.example.study.webSocket;

import com.alibaba.fastjson.JSONObject;
import com.example.study.commen.websocket.WebServiceImpl;
import com.example.study.commen.websocket.WebSocketSever;
import com.example.study.commen.websocket.bean.WebSocketVO;
import com.example.study.config.JsonResult;
import com.example.study.plus.mybatis_plus.entity.ChatMessages;
import com.example.study.plus.mybatis_plus.service.ChatMessagesService;
import com.example.study.rabbitmq.config.RabbitmqInfo;
import com.github.linyuzai.connection.loadbalance.websocket.concept.WebSocketLoadBalanceConcept;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@Api(description = "WebSocket控制")
@RestController
@RequestMapping(value = "/socket")
public class WebSocketController {

    @Resource
    WebSocketSever webSocketSever;

    @Resource
    RabbitTemplate rabbitTemplate;

    @ApiOperation(value = "发送消息给指定用户")
    @PostMapping(value = "/sendMsg")
    @CrossOrigin(origins = "http://localhost:8080")
    public JsonResult<String> sendMsg(@ApiParam("fromId") @RequestParam int fromId,@ApiParam("targetId") @RequestParam int targetId,@ApiParam("message") @RequestParam String message) {
        JsonResult<String> result=new JsonResult<>();
        WebSocketVO webSocketVO = new WebSocketVO();
        webSocketVO.setFromId(fromId);
        webSocketVO.setTargetId(targetId);
        webSocketVO.setMessage(message);
        String s = webSocketSever.sendMessageByUser(webSocketVO);
        result.code=200;
        result.message=s;

        //
        if (s.equals("success")||s.equals("offline")){
            ChatMessages chatMessages = new ChatMessages();
            chatMessages.setSenderId(fromId);
            chatMessages.setReceiverId(targetId);
            chatMessages.setMessage(message);
            chatMessages.setPushed(s.equals("success"));
            rabbitTemplate.convertAndSend(RabbitmqInfo.exchangeName, "chatKey", chatMessages);
        }

        //end

        return result;
    }
//https://github.com/Linyuzai/concept/wiki/Concept-WebSocket-LoadBalance
//    @Autowired
//    private WebSocketLoadBalanceConcept concept;
//    public JsonResult<String> sendMsg2(){
//
//        return new JsonResult<>();
//    }
}
